﻿namespace MetaDrive.VisualStudio.Linq
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using EnvDTE;
    using EnvDTE80;

    public sealed class ProjectIterator : IEnumerable<Project>
    {
        private readonly Solution _solution;

        public ProjectIterator(Solution solution)
        {
            if (solution == null)
                throw new ArgumentNullException("solution");

            this._solution = solution;
        }

        public IEnumerator<Project> GetEnumerator()
        {
            foreach (Project project in this._solution.Projects)
            {
                if (project.Kind != EnvDTE80.ProjectKinds.vsProjectKindSolutionFolder)
                {
                    yield return project;
                }
                else
                {
                    foreach (Project subProject in Enumerate(project))
                    {
                        yield return subProject;
                    }
                }
            }
        }

        IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        private IEnumerable<Project> Enumerate(Project project)
        {
            foreach (ProjectItem item in project.ProjectItems)
            {
                if (item.Object is Project)
                {
                    if (((Project)item.Object).Kind != ProjectKinds.vsProjectKindSolutionFolder)
                    {
                        yield return (Project)item.Object;
                    }
                    else
                    {
                        foreach (Project subProject in Enumerate((Project)item.Object))
                        {
                            yield return subProject;
                        }
                    }
                }
            }
        }
    }
}
